<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <tree-table :data="list" :expand-all="true" border>
      <el-table-column :label="$t('table.id')">
        <template slot-scope="scope">
          <span >{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.available')">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_available | availableFilter">{{ scope.row.available_name }}</el-tag>
        </template>
      </el-table-column>
       <!-- <el-table-column :label="$t('table.sort')" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="Operation" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button size="mini" type="danger" @click="openDel(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </tree-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="900px">
      <el-form ref="dataForm" :rules="rules" :model="temp"  label-width="70px" style="margin-left:50px;">
        <el-form-item :label="$t('table.category')">
            <el-cascader
              :placeholder="$t('placeholder.select')"
              v-model="temp.category_id"
              :options="categoryOptions"
              change-on-select
            ></el-cascader>
            <!-- <el-select v-model="temp.category_id" class="filter-item" :placeholder="$t('placeholder.select')">
              <el-option v-for="(item, index) in categoryOptions" :key="index" :label="item.name" :value="item.id" />
            </el-select> -->
          </el-form-item>
        <el-form-item :label="$t('table.available')">
          <el-radio v-model="temp.is_available" label="1" name="is_avaliable">{{ $t('table_element.available.on') }}</el-radio>
          <el-radio v-model="temp.is_available" label="0" name="is_avaliable">{{ $t('table_element.available.un') }}</el-radio>
        </el-form-item>
        <!-- <el-form-item :label="$t('table.sort')">
            <el-input v-model="temp.sort" name="sort" min="0" type="number" style="width: 100px" />
          </el-form-item> -->
        <template>
          <el-tabs v-model="activeName" >
            <el-tab-pane label="en" name="first">
              <el-form-item :label="$t('table.name')" required prop="name">
                <el-input v-model="temp.name" name="name" />
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-cn" name="second">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.cnname" name="cnname" />
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-hk" name="third">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.hkname" name="hkname" />
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-tw" name="fourth">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.twname" name="twname" />
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="delVisible"
      width="30%"
      >
      <span>{{$t('table.delInfo')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="danger" @click="deleteData">{{$t('table.delete')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import articleCategoryApi from '@/api/article/articlecategory'
// import { fetchList, fetchCategory, createCategory, updateCategory, deleteCategory, fetchCategoryAll, fetchCategoryTree, fetchCategoryTreeList } from '@/api/nutrition'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import treeTable from '@/components/TreeTable'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Tinymce from '@/components/Tinymce'
import i18n from '@/lang/index'
// import treeToArray from './customEval'

export default {
  name: 'Benefit',
  components: { Pagination, Tinymce, treeTable },
  directives: { waves },
  filters: {
    availableFilter(status) {
      const availableMap = [
        'danger',
        'success'
      ]
      return availableMap[status]
    }
  },
  data() {
    return {
      // func: treeToArray,
      activeName: 'first',
      expandAll: false,
      delVisible: false,
      cRow: {},
      isAvailable: 2,
      tableKey: 0,
      list: [],
      content: ``,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        available: 2,
        name: '',
        lang: i18n.locale,
      },
      availableOptions: [{ 'value': 2, 'name': i18n.t('table_element.available.all') }, { 'value': 1, 'name': i18n.t('table_element.available.on') }, {'value': 0, 'name': i18n.t('table_element.available.un') }],
      // areaOptions: [{ name : '中国香港', id: 1 }, { name : '中国大陆', id: 2 }],
      categoryOptions: [],
      showReviewer: false,
      temp: {
        id: '',
        pid: '0',
        is_available: "1",
        sort: 0,
        name: '',
        cnname: '',
        hkname: '',
        twname: '',
        area: 96,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getCategoryList()
  },
  computed: {
    // areaOptions: function () {
    //     return this.$store.state.locale.areas
    // },
    // categoryOptions: function () {
    //     return this.$store.state.locale.categoryTree
    // }
  },
  methods: {
    censor(censor) {
      var i = 0
      return function(key, value) {
        if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value) 
          return '[Circular]';

        if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
          return '[Unknown]'

        ++i // so we know we aren't using the original object anymore

        return value
      }
    },
    getList() {
      this.listLoading = true
      articleCategoryApi.fetchCategoryTreeList(this.listQuery).then(response => {
        // console.log(response.data.data)
        var data = response.data
        this.list = data.data
        // this.total = data.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getCategoryList() {
      articleCategoryApi.fetchCategoryTree().then(response => {
        var data = response.data
        this.categoryOptions = data.data
      });
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: 'Success！',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        pid: '0',
        is_available: '1',
        sort: 0,
        name: '',
        cnname: '',
        hkname: '',
        twname: '',
        area: 96,
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      // 弹窗↓
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          this.temp.lang = i18n.locale
          articleCategoryApi.storeRecord(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Create Success！',
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.$store.dispatch('setArticleCategory').then(res => {})
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, JSON.parse(JSON.stringify(row, this.censor(row)))) // copy obj
      this.temp.is_available = this.temp.is_available.toString()
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.temp.timestamp = new Date()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lang = i18n.locale
          let tempData = Object.assign({}, this.temp)
          console.log('tempData', tempData)
          // tempData.timestamp = new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          // console.log('tempData.timestamp22', tempData.timestamp)
          articleCategoryApi.updateRecord(this.temp.id, tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Success！',
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.$store.dispatch('setArticleCategory').then(res => {})
          })
        }
      })
    },
    handleDelete(row) {
      console.log(row);
      this.$notify({
        title: 'Success',
        message: 'Delete Success！',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    openDel(row){
      this.cRow = row
      this.delVisible = true
    },
    deleteData() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        let row = this.cRow
        this.delVisible = false
        articleCategoryApi.destroyRecord(row.id).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success！',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.$store.dispatch('setArticleCategory').then(res => {})
          }

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
